import datetime
from json import dumps
from random import randrange

from flask import Flask, render_template, request

from pyecharts import options as opts
from pyecharts.charts import Bar, Line

import stock
import stockranking
from database import DataBase
from stock import Stock

app = Flask(__name__, static_folder="templates")


def bar_base() -> Bar:
    c = (
        Bar()
            .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
            .add_yaxis("商家A", [randrange(0, 100) for _ in range(6)])
            .add_yaxis("商家B", [randrange(0, 100) for _ in range(6)])
            .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题"))
    )
    return c


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/barChart")
def get_bar_chart():
    c = bar_base()
    return c.dump_options_with_quotes()


@app.route("/stocks")
def stocks():
    __db = DataBase("data.db")
    try:
        result = __db.query("select name, code, count(1) as total from lgt_100 group by name, code order by total desc",
                            {})
        __stocks = []
        for res in result:
            s = Stock(res[0], res[1])
            __stocks.append(s)
        return dumps(__stocks, default=stock.convert_2_json)
    finally:
        __db.close()


@app.route("/stock", )
def get_stocks():
    __code = request.args.get("code")
    __name = request.args.get("name")
    start_date = request.args.get("start_date")
    current_date = datetime.date.today()
    if start_date is None or start_date == '':
        start_date = datetime.date(current_date.year, 1, 1).isoformat()
    end_date = request.args.get("end_date")
    if end_date is None or end_date == '':
        end_date = current_date.isoformat()
    db = DataBase("data.db")
    try:
        result = db.query(
            "select code, price, percent,  day,total from lgt_100 where code = ? and day >= ? and day <= ?",
            [__code, start_date, end_date])
        __priceAxis = []
        __percentAxis = []
        __dateAxis = []

        for res in result:
            __priceAxis.append(res[1])
            __percentAxis.append(res[2])
            __dateAxis.append(res[3])

        line = (
            Line()
                .add_xaxis(xaxis_data=__dateAxis)
                .add_yaxis(series_name="股价", stack="总量", y_axis=__priceAxis)
                .extend_axis(
                yaxis=opts.AxisOpts(type_="value", is_scale=True, is_inverse=False))
                .set_global_opts(title_opts=opts.TitleOpts(pos_left='center', pos_top='2%', title=__name + "走势图"),
                                 legend_opts=opts.LegendOpts(pos_top='6%'),
                                 tooltip_opts=opts.TooltipOpts(trigger="axis"),
                                 yaxis_opts=opts.AxisOpts(
                                     type_="value",
                                     is_scale=True,
                                     axistick_opts=opts.AxisTickOpts(is_show=True),
                                     splitline_opts=opts.SplitLineOpts(is_show=True),
                                     axislabel_opts=opts.LabelOpts(formatter="{value}元")
                                 ),

                                 xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=True),
                                 datazoom_opts=opts.DataZoomOpts(type_="slider", range_start=0, range_end=100))
        )

        __line2 = (
            Line()
                .add_xaxis(xaxis_data=__dateAxis)
                .add_yaxis(series_name="北向资金占流通股比例", stack='总量1', y_axis=__percentAxis, yaxis_index=1)
        )

        c = line.overlap(__line2)
        return c.dump_options_with_quotes()
    finally:
        db.close()


@app.route("/stock/ranking")
def get_top_stocks():
    __db = DataBase("data.db")
    start_date = request.args.get("start_date")
    current_date = datetime.date.today()
    if start_date is None or start_date == '':
        start_date = datetime.date(current_date.year, 1, 1).isoformat()

    end_date = request.args.get("end_date")
    if end_date is None or end_date == '':
        end_date = current_date.isoformat()

    size = request.args.get("size")
    if size is None or size == '':
        size = 100
    try:
        __sql = '''
                    select t1.code,t1.name, t1.price new_price, ifnull(t2.price,0) old_price, t1.weight new_weight, t2.weight old_weight, (t2.weight-t1.weight) as ranking
                    from 
                    (select * from lgt_100 where day = (select max(day)  from lgt_100 where day <= ?)) t1 
                    left join 
                    (select * from lgt_100 where day = (select max(day)  from lgt_100 where day <= ?)) t2 on t1.code = t2.code
                    order by ranking desc
                    limit ?
                    '''
        result = __db.query(__sql, [end_date,start_date,int(size)])

        __ranking = []
        for row in result:
            s = stockranking.StockRank(row[0], row[ 1],
                                       row[2], row[3],
                                       row[4], row[5],
                                       row[6])
            __ranking.append(s)

        # return dumps(__ranking, default=stockranking.convert_2_json)

        return render_template("stock_ranking.html", start_date=start_date, end_date=end_date, stock_rankings=__ranking)
    finally:
        __db.close()


if __name__ == "__main__":
    app.run(debug=True)
